package com.my.test.classload;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Date;

public class MyClassLoader extends ClassLoader {



    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        System.out.println("你好啊啊啊啊啊");
        byte[] data = this.loadClassData(name);
        return this.defineClass(name, data, 0, data.length);
    }

    private byte[] loadClassData(String name) {
        try {
            // 传进来是带包名的
            name = name.replace(".", "//");
            File file = new File("D:\\softdata\\ideaProjects\\MyProject\\out\\production\\MyProject\\" + name + ".class");
            System.out.println("上次修改："+ new Date(file.lastModified()));
            FileInputStream inputStream = new FileInputStream(new File("D:\\softdata\\ideaProjects\\MyProject\\out\\production\\MyProject\\" + name + ".class"));
            // 定义字节数组输出流
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int b = 0;
            while ((b = inputStream.read()) != -1) {
                baos.write(b);
            }
            inputStream.close();
            return baos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
